package service

import (
	"fmt"
	"github.com/asaskevich/govalidator"
	"github.com/gin-gonic/gin"
	"net/http"
	"worklog/models"
)

// GetMessage 获取所有信息
// @Tags 信息模块
// @Success 200 {string} json["code","message","data"]
// @Router /message [get]
func GetMessage(c *gin.Context) {
	data := models.GetMessage()
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "success",
		"data":    data,
	})
}

// CreateMessage
// @Summary 新增信息
// @Tags 信息模块
// @param name formData string false "用户名"
// @param password formData string false "密码"
// @param now_date formData string false "工作日期"
// @param work_content formData string false "工作内容"
// @param work_time formData string false "工作时长"
// @Sources 200 {string} json{"code","message","data"}
// @Router /message [post]
func CreateMessage(c *gin.Context) {
	const (
		errorPasswordMessage   = "input passwd is different"
		errorMessageEmpty      = "write message must not empty"
		errorUserMessageExists = "User is not exists"
		successMessage         = "add message success"
	)
	message := models.Message{}
	message.UserName = c.PostForm("name")
	message.PassWord = c.PostForm("password")
	message.NowDate = c.PostForm("now_date")
	message.WorkContent = c.PostForm("work_content")
	message.WorkTime = c.PostForm("work_time")
	_, err := govalidator.ValidateStruct(message)
	if err != nil {
		fmt.Println(err)
		return
	}
	if message.UserName == "" || message.WorkContent == "" || message.NowDate == "" || message.WorkTime == "" || message.PassWord == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": errorMessageEmpty,
		})
		return
	}
	data := models.FindUserBYUsername(message.UserName)
	if data.UserName == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": errorUserMessageExists,
		})
		return
	}
	password := models.GetPasswordByUsername(message.UserName)
	if message.PassWord != password {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  errorPasswordMessage,
		})
	} else {
		err := models.CreateMessage(message)
		if err != nil {
			fmt.Println(err)
		}
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": successMessage,
			"data":    message,
		})
	}

}
